package com.huajx.tuopuda.client.udp.codec;

import com.huajx.core.util.BitUtil;
import com.huajx.tuopuda.client.udp.TuopudaMessage;
import com.huajx.tuopuda.client.udp.TuopudaUtil;

/**
 *
 * 编码解码器
 *
 * @author: lisa 叶新华
 * @create: 2019-09-27 17:39
 */
public abstract class AbstractCodec {
    private int sn;
    public abstract byte[] encode();

    public void decode(byte[] bytes){
    }

    protected byte[] encode(int sn, int function, Encode encode) {
        byte[] bytes = new byte[34];
        int checkSum = 0;   // 校验和
        bytes[0] = 0x7E;    // 开始位
        bytes[33] = 0x0D;   // 结束位

        checkSum += TuopudaUtil.replaceBytes(bytes, sn, 1, 2);
        checkSum += TuopudaUtil.replaceBytes(bytes, function, 3, 2);

        if (encode != null) {
            checkSum += encode.encode(bytes);
        }

        TuopudaUtil.replaceBytes(bytes, checkSum, 31, 2); //补较验和
        return bytes;
    }

    public void decode(){}

    public int getSn() {
        return sn;
    }

    public void setSn(int sn) {
        this.sn = sn;
    }



    public interface Encode {
        int encode(byte[] bytes);
    }

    public interface Decode {
        void decode(byte[] bytes);
    }
}
